<?php
/**
 * User: madis
 * Date: 26.09.2009
 * Time: 11:31:22
 */



class ICSConverter {

    private $allEventsContent = '';

    public function __construct($XMLContent) {
        $this->addICSHeader();
        $this->xmlToICS($XMLContent);
        $this->addICSFooter();
    }

    public function getICSContent() {
        return $this->allEventsContent;
    }

    private function xmlToICS($XMLContent) {
        require_once('xml2array.php');

        $timetable = xml2array($XMLContent);

        define('ACADEMIC_YEAR', 2009);
        define('FIRST_WEEK_OF_ACADEMIC_YEAR', $this->findFirstWeekOfAcademicYear());

            // With each day
        foreach ($timetable['RG_YLIOP_TUNNIPLAAN']['LIST_G_KL_NADALAPAEV']['G_KL_NADALAPAEV'] as $weekday) {
            // With each lesson
            foreach ($weekday['LIST_G_ALGUSKELL']['G_ALGUSKELL'] as $lessonInfo) {
                if (!empty($lessonInfo)) {
                    $lesson = new Lesson($lessonInfo, $weekday['KL_NADALAPAEV']);
                    $this->addToContent($lesson->getContent());
                }
            }
        }
    }

    private function findFirstWeekOfAcademicYear() {

        $weekNumber = date("W", mktime(9, 1, 0, 9, 1, ACADEMIC_YEAR))-1;
            //echo $weekNumber;
            //$weekNumber = 35;

        return $weekNumber;
    }

    private function addToContent($outcomeCache) {
        $this->allEventsContent .= $outcomeCache;
    }

    private function addICSHeader() {
        $icsHeader = 'BEGIN:VCALENDAR
PRODID:-//Taksikoer//Tartu Ülikooli Õppeinfosüsteem//EN
VERSION:2.0
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Tallinn
BEGIN:DAYLIGHT
TZOFFSETFROM:+0200
TZOFFSETTO:+0300
TZNAME:EEST
DTSTART:19700329T030000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0300
TZOFFSETTO:+0200
TZNAME:EET
DTSTART:19701025T040000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE'."\n";

        $this->allEventsContent .= $icsHeader;
    }

    private function addICSFooter() {
        $icsFooter = 'END:VCALENDAR';
        $this->allEventsContent .= $icsFooter;
    }

}
